<!--角色分配菜单-->
<template>
  <div>
    <el-tree :data="roleMenus"
             :props="defaultProps"
             @check="handleCheck"
             @current-change="handleChange"
             @check-change="handChangeNode"
             @node-click="handleNodeClick(roleMenus)"
             ref="menu-tree"
             show-checkbox
             default-expand-all
             :default-checked-keys="checkedIds"
             node-key="menuId"
    ></el-tree>
    <el-button type="primary" @click="onSave">保存</el-button>
    <el-button @click="handleClear()">清空</el-button>
    <el-button @click="handleBack">返回</el-button>
  </div>
</template>
<script>
import {gainRoleMenus, setRoleMenus} from "@/api/roles/roles";

export default {
  //搭配路由写法
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  name: "AllocMenuIndex",
  data() {
    return {
      //节点改变数据
      changeNode: [],
      //角色菜单列表
      roleMenus: [],
      //显示的格式children 子节点,label是显示的属性
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      checkedIds: []
    };
  },
  created() {
    this.loadRoleMenus()
  },
  methods: {
    //加载角色对应的菜单列表
    loadRoleMenus() {
      gainRoleMenus(this.roleId).then(res => {
        console.log("加载角色对应的菜单列表:", res);
        if (res.data.code == '200') {
          this.roleMenus = res.data.data;
          //排除有子菜单的父菜单id,添加无子菜单的id
          const checkedIds = this.getSelectIds(this.roleMenus);
          this.checkedIds = checkedIds;
          //让树节点默认被选中
          //等待渲染this.roleMenus
          // this.$nextTick(() => {
          //   this.$refs['menu-tree'].setCheckedKeys(checkedIds)
          // })
          // queueMicrotask(()=>{})
          // setTimeout(()=>{})
        } else {
          this.$message.error('获取角色菜单信息失败!')
        }
      })
    },
    //当复选框被点击的时候触发
    //传递给 data 属性的数组中该节点所对应的对象、树目前的选中状态对象
    // checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys
    handleCheck(checkedNodes,checkedKeys) {
      //改变的节点
      this.changeNode=[]
      for (let i = 0; i < checkedKeys.checkedKeys.length; i++) {
        this.changeNode[i]=(checkedKeys.checkedKeys[i])
      }
      console.log("checkedNodes", checkedNodes);
      console.log("checkedKeys", checkedKeys);
      // console.log("halfCheckedNodes", halfCheckedNodes);
      // console.log("halfCheckedKeys", halfCheckedKeys);
    },
    //当前选中节点变化时触发的事件
    //参数:当前节点的数据，当前节点的 Node 对象
    // eslint-disable-next-line no-unused-vars
    handleChange(curNode, curNodeList) {
      // console.log("当前选中节点变化时触发的事件", curNode, curNodeList)
    },
    //节点选中状态发生变化时的回调
    //传递给 data 属性的数组中该节点所对应的对象、节点本身是否被选中、节点的子树中是否有被选中的节点
    // eslint-disable-next-line no-unused-vars
    handChangeNode(data, curNodeSelect, childrenSelect) {
      // console.log(" data 属性的数组:",data);
      // console.log(" 节点本身是否被选中:",curNodeSelect);
      // console.log(" 节点的子树中是否有被选中的节点:",childrenSelect);

    },
    //节点被点击时的回调
    // eslint-disable-next-line no-unused-vars
    handleNodeClick(roleMenus) {
      // console.log("点击回调的data数据:",roleMenus);
    },
    //把cheked为true的数据返回成一个数组
    getSelectIds(menuArr) {
      console.log("menuArr", menuArr);
      let ids = [];
      menuArr.forEach(menu => {
        // debugger
        //规则1:如果菜单有子菜单,就只考虑子菜单,父级别的状态不考虑
        //规则2:如果菜单无子菜单，并且它标记为true,就保存它的id
        if (menu.children.length > 0) {
          const tmpArr = this.getSelectIds(menu.children)
          // ids=[...ids,...tmpArr]
          ids = ids.concat(tmpArr)
        } else if (menu.checked == true) {
          ids.push(menu.menuId)
        }
      })
      return ids;
    },
    //清空所有选项
    handleClear() {
      this.$refs['menu-tree'].setCheckedKeys([])
    },
    //给角色分配菜单
    //this.$refs['menu-tree'].getCheckedKeys() 当前选中的节点id
    onSave() {
      const data = {
        flag: 'menu',
        roleId: this.roleId,
        //被操作的节点
        nodeIdSelect:this.changeNode,
        checked:true
      };
      console.log("NodeIdSelect",this.changeNode);
      setRoleMenus(data).then(res => {
        if (res.data.code == '200') {
          this.$message.success('分配菜单操作成功!')
        } else {
          this.$message.error('分配菜单操作失败！')
        }
      }).catch(e=>{
        console.log("错误信息::::",e)
      }).finally(() => {
        this.$router.push({name: 'roles'})
      })
    },
    handleBack(){
      this.$router.push({name: 'roles'})
    }
  }
}
</script>


<style scoped>
.el-tree {
  margin-bottom: 20px;
}
</style>
